﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Casamiel.Application;
using Casamiel.Common.Extensions;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers
{
    /// <summary>
    /// SC ontroller.
    /// </summary>
    [ApiVersionNeutral]
    [Route("api/[controller]")]
    [ApiController]

    public class SController : Controller
    {
        private readonly System.Net.Http.IHttpClientFactory _clientFactory;
        private readonly IStoreService _storeService;
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Controllers.SController"/> class.
        /// </summary>
        /// <param name="clientFactory">Client factory.</param>
        /// <param name="storeService">Store service.</param>
        public SController(IHttpClientFactory clientFactory,IStoreService storeService){
            _clientFactory = clientFactory;
            _storeService = storeService;
        }
        /// <summary>
        /// Index this instance.
        /// </summary>
        /// <returns>The index.</returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult>Index111()
        {
            string ad =  "";
            var ImageList = new List<string>(ad.Split(new[] { "," }, StringSplitOptions.None));
            Console.WriteLine(JsonConvert.SerializeObject(ImageList));

            //FileStream fs = new FileStream($"{AppContext.BaseDirectory}//logs//{DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")}//ResponseTimeService.log", FileMode.Open, FileAccess.Read);
            //List<string> list = new List<string>();
            //StreamReader sr = new StreamReader(fs);
            //sr.BaseStream.Seek(0, SeekOrigin.Begin);
            //string temp = await sr.ReadLineAsync();
            //Regex reg =new Regex(@"StatusCode:(\d*)");// new Regex(@"执行时间(\d*)");

            //while (temp != null) {


            //    Match match = reg.Match(temp);
            //    if (match.Groups[1].Value.ToInt32(0) ==401) {
            //        list.Add(temp);
            //    }
            //    //if (match.Groups[1].Value.ToInt32(0) > 500 && match.Groups[1].Value.ToInt32(0)<1000) {
            //    //    list.Add(temp);
            //    //}

            //    temp = await sr.ReadLineAsync();
            //}
            ////关闭此StreamReader对象 
            //sr.Close();
            //fs.Close();

            var list = await _storeService.GetAllStoreByNameAsync<ICasaMielSession>("").ConfigureAwait(false);
            foreach (var item in list) {
                if (item.StoreId >134 ) {
                    await GetQRCode(item.RelationId.ToString(CultureInfo.CurrentCulture), item.StoreName).ConfigureAwait(false);
                }
            }
            return Ok(list);
        }
        /// <summary>
        /// Gets the QRC ode.
        /// </summary>
        /// <returns>The QRC ode.</returns>
        /// <param name="shopid">Shopid.</param>
        /// <param name="storename">Storename.</param>
        /// <param name="a">The alpha component.</param>
        private async Task GetQRCode (string shopid,string storename,string a="")
        {
            a = "24_KJX4YDBVUUNH-LyIuxwyTRUfvKIbXRwt5GyvCZH2v4EeM7hWbyMS0rJIn8oXKNTjuU3Ctr6TRVZM2Ij9hvG1PFCI_v8rHFdBQM6ehyUaNSxBENige_FI6H6vPXJNrRZGviu5p-ObE57VfEReQJBaAGAZSK";
            string path = $"{ AppContext.BaseDirectory}//logs//shop//{shopid}_{storename}.png";
            var client = _clientFactory.CreateClient("");
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={a}"))
            {
                var data = new { scene = $"shopid={shopid}", width = 1280 };
                requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json");
                using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                        {
                            byte[] bytes = new byte[stream.Length];
                            stream.Read(bytes, 0, bytes.Length);
                            // 设置当前流的位置为流的开始
                            stream.Seek(0, SeekOrigin.Begin);
                            await System.IO.File.WriteAllBytesAsync(path, bytes).ConfigureAwait(false);
                        }
                        

                        // return File(result, "image/jpeg");
                    }
                }
            }


        }
    }
}
